import os
import sys
from datetime import datetime
from PyQt5.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                            QPushButton, QTabWidget, QGroupBox, QTextEdit, QMessageBox,
                            QApplication)
from PyQt5.QtGui import QFont, QTextCursor, QIcon
from PyQt5.QtCore import Qt, QThread

from modules.gui.settings_tab import SettingsTab
from modules.gui.accounts_tab import AccountsTab
from modules.gui.results_tab import ResultsTab
from modules.workers.register_worker import RegisterWorker

class CursorRegisterGUI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Cursor账号注册工具")
        self.resize(1000, 700)
        
        # 设置应用程序图标
        icon_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "favicon.ico")
        if os.path.exists(icon_path):
            self.setWindowIcon(QIcon(icon_path))
        
        # Set up central widget
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # Main layout
        main_layout = QVBoxLayout(central_widget)
        
        # Create tab widget
        self.tabs = QTabWidget()
        self.tabs.setTabPosition(QTabWidget.North)  # Tabs at the top
        
        # Create tabs
        self.settings_tab = SettingsTab()
        self.accounts_tab = AccountsTab()
        self.results_tab = ResultsTab()
        
        # Add tabs to tab widget
        self.tabs.addTab(self.settings_tab, "注册设置")
        self.tabs.addTab(self.accounts_tab, "账号管理")
        self.tabs.addTab(self.results_tab, "注册结果")
        
        # Add tab widget to main layout
        main_layout.addWidget(self.tabs)
        
        # Create log area
        self.create_log_panel(main_layout)
        
        # Bottom buttons
        button_layout = QHBoxLayout()
        
        # 开始注册按钮
        self.start_button = QPushButton("开始注册")
        self.start_button.clicked.connect(self.start_registration)
        self.start_button.setMinimumHeight(40)
        self.start_button.setFont(QFont("Arial", 12, QFont.Bold))
        button_layout.addWidget(self.start_button)
        
        # 停止注册按钮 - 与开始注册按钮风格一致
        self.stop_button = QPushButton("停止注册")
        self.stop_button.clicked.connect(self.stop_registration)
        self.stop_button.setMinimumHeight(40)
        self.stop_button.setFont(QFont("Arial", 12, QFont.Bold))
        self.stop_button.setEnabled(False)  # Disabled initially
        button_layout.addWidget(self.stop_button)
        
        main_layout.addLayout(button_layout)
        
        # Registration worker
        self.worker = None
        
        # Show network environment notice
        self.show_network_notice()
    
    def show_network_notice(self):
        """显示网络环境提示"""
        QMessageBox.information(
            self,
            "网络环境提示",
            "注意：大陆用户可能需要特殊网络环境支持才能使用此程序正常注册Cursor账号。\n\n"
            "请确保您的网络环境能够正常访问Cursor相关服务。"
        )
    
    def create_log_panel(self, parent_layout):
        group_box = QGroupBox("操作日志")
        layout = QVBoxLayout()
        
        self.log_text = QTextEdit()
        self.log_text.setReadOnly(True)
        self.log_text.setMaximumHeight(150)  # Limit log area height
        layout.addWidget(self.log_text)
        
        group_box.setLayout(layout)
        parent_layout.addWidget(group_box)
        
    def log_message(self, message):
        """
        Add a message to the log
        """
        self.log_text.append(f"[{datetime.now().strftime('%H:%M:%S')}] {message}")
        # Scroll to bottom
        self.log_text.moveCursor(QTextCursor.End)
        # Process events to update UI immediately
        QApplication.processEvents()
    
    def start_registration(self):
        """
        Start the registration process
        """
        # Save current accounts
        if not self.accounts_tab.save_accounts():
            return
        
        # 获取待注册账号（已排除已注册的）
        accounts = self.accounts_tab.get_accounts()
        if not accounts:
            QMessageBox.warning(self, "警告", "没有账号可用于注册或所有账号已注册")
            return
            
        reply = QMessageBox.question(
            self, "确认", f"找到 {len(accounts)} 个待注册账号，确定要开始注册吗？\n"
                       f"注册数量将被限制为 {min(self.settings_tab.number_spin.value(), len(accounts))} 个",
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No
        )
        
        if reply != QMessageBox.Yes:
            return
        
        # 清空日志
        self.log_text.clear()
        
        # Update UI buttons
        self.start_button.setEnabled(False)
        self.start_button.setText("注册中...")
        self.stop_button.setEnabled(True)
        
        # Get settings
        settings = self.settings_tab.get_settings()
        
        # Create and start worker thread
        self.worker = RegisterWorker(
            min(settings["number"], len(accounts)),  # 限制注册数量为待注册账号数量
            settings["max_workers"],
            settings["enable_headless"],
            settings["enable_browser_log"],
            settings["hide_account_info"],
            settings.get("auto_close_browser", True)  # 添加自动关闭浏览器选项
        )
        
        # Add chrome settings if available
        if "chrome_settings" in settings:
            self.worker.chrome_settings = settings["chrome_settings"]
        
        # 传递日志回调
        self.worker.set_log_callback(self.log_message)
        
        # Connect signals
        self.worker.update_signal.connect(self.log_message)
        self.worker.result_signal.connect(self.update_results)
        self.worker.finished_signal.connect(self.on_registration_finished)
        
        # Start worker thread
        self.worker.start()
    
    def stop_registration(self):
        """
        Stop the registration process forcibly
        """
        if not self.worker:
            return
            
        reply = QMessageBox.question(
            self, "确认", "确定要强制停止当前的注册过程吗？\n这可能会导致正在进行的注册失败。",
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No
        )
        
        if reply != QMessageBox.Yes:
            return
            
        self.log_message("正在强制停止注册过程...")
        
        # Tell the worker to stop
        if hasattr(self.worker, 'stop_requested'):
            self.worker.stop_requested = True
        
        # Force terminate if necessary (safer approach would have timeouts and proper cleanup)
        if self.worker.isRunning():
            self.worker.terminate()
            self.worker.wait(3000)  # Wait up to 3 seconds for termination
            
            if self.worker.isRunning():
                self.log_message("警告：无法正常停止线程，正在强制终止...")
                # Additional measures could be taken here
        
        self.log_message("注册过程已停止")
        self.on_registration_finished()
    
    def update_results(self, results):
        """
        Update the results tab with new data
        """
        self.results_tab.update_results(results)
        
        # 重新加载账号管理页的账号，以更新状态
        self.accounts_tab.load_existing_accounts()
        
        # Switch to results tab
        self.tabs.setCurrentWidget(self.results_tab)
    
    def on_registration_finished(self):
        """
        Handle registration finished
        """
        # Re-enable start button
        self.start_button.setEnabled(True)
        self.start_button.setText("开始注册")
        self.stop_button.setEnabled(False)
        
        # Release worker thread
        self.worker = None
        
        # 重新加载账号管理页的账号，以更新状态
        self.accounts_tab.load_existing_accounts() 